<template>
    <div class="admin-dashboard">
        <!-- 顶部导航 -->
        <div class="admin-header">
            <div class="header-left">
                <div class="logo-section">
                    <img class="logo" src="../../assets/svg/logo.svg" />
                    <h1 class="app-name">学了么 - 管理员控制台</h1>
                </div>
            </div>
            <div class="header-right">
                <div class="admin-info">
                    <span>欢迎，{{ adminInfo.nickname || adminInfo.username }}</span>
                </div>
                <button @click="logout" class="logout-btn">退出登录</button>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="admin-content">
            <!-- 侧边栏菜单 -->
            <div class="admin-sidebar">
                <div class="menu-list">
                    <div 
                        class="menu-item" 
                        :class="{ active: activeMenu === 'message' }"
                        @click="setActiveMenu('message')"
                    >
                        <i class="icon">📧</i>
                        <span>消息管理</span>
                    </div>
                    <div 
                        class="menu-item" 
                        :class="{ active: activeMenu === 'order' }"
                        @click="setActiveMenu('order')"
                    >
                        <i class="icon">📦</i>
                        <span>订单管理</span>
                    </div>
                    <div 
                        class="menu-item" 
                        :class="{ active: activeMenu === 'member' }"
                        @click="setActiveMenu('member')"
                    >
                        <i class="icon">👑</i>
                        <span>会员管理</span>
                    </div>
                    <div 
                        class="menu-item" 
                        :class="{ active: activeMenu === 'report' }"
                        @click="setActiveMenu('report')"
                    >
                        <i class="icon">📊</i>
                        <span>报表设计</span>
                    </div>
                </div>
            </div>

            <!-- 右侧内容区 -->
            <div class="admin-main">
                <!-- 订单管理页面 -->
                <div v-if="activeMenu === 'order'" class="module-content">
                    <OrderManagement />
                </div>

                <!-- 会员管理页面 -->
                <div v-else-if="activeMenu === 'member'" class="module-content">
                    <MemberManagement />
                </div>

                <!-- 消息管理页面 -->
                <div v-else-if="activeMenu === 'message'" class="module-content">
                    <div class="module-header">
                        <h2>消息发送</h2>
                        <p>向指定用户发送系统通知消息</p>
                    </div>

                    <div class="message-form-card">
                        <form @submit.prevent="sendMessage" class="message-form">
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="userId">目标用户ID</label>
                                    <input 
                                        type="number" 
                                        id="userId" 
                                        v-model="messageForm.userId" 
                                        placeholder="请输入用户ID（留空则发送给ID为10的默认用户）"
                                    />
                                </div>
                                <div class="form-group">
                                    <label for="messageType">消息类型</label>
                                    <select id="messageType" v-model="messageForm.messageType">
                                        <option value="1">普通通知</option>
                                        <option value="2">重要通知</option>
                                        <option value="3">紧急通知</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="messageTitle">消息标题</label>
                                <input 
                                    type="text" 
                                    id="messageTitle" 
                                    v-model="messageForm.messageTitle" 
                                    placeholder="请输入消息标题（留空则使用默认标题）"
                                />
                            </div>

                            <div class="form-group">
                                <label for="messageContent">消息内容</label>
                                <textarea 
                                    id="messageContent" 
                                    v-model="messageForm.messageContent" 
                                    placeholder="请输入消息内容（留空则使用默认内容）"
                                    rows="4"
                                ></textarea>
                            </div>

                            <div class="form-actions">
                                <button type="submit" class="send-btn" :disabled="sending">
                                    {{ sending ? '发送中...' : '发送消息' }}
                                </button>
                                <button type="button" @click="resetForm" class="reset-btn">
                                    重置表单
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- 发送历史 -->
                    <div class="message-history">
                        <h3>最近发送记录</h3>
                        <div class="history-list">
                            <div 
                                v-for="(record, index) in messageHistory" 
                                :key="index"
                                class="history-item"
                            >
                                <div class="history-info">
                                    <div class="history-title">{{ record.title }}</div>
                                    <div class="history-details">
                                        发送给用户ID: {{ record.userId }} | 
                                        类型: {{ getMessageTypeName(record.type) }} | 
                                        时间: {{ record.time }}
                                    </div>
                                </div>
                                <div class="history-status" :class="record.status">
                                    {{ record.status === 'success' ? '成功' : '失败' }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 报表设计页面 -->
                <div v-else-if="activeMenu === 'report'" class="module-content">
                    <div class="module-header">
                        <h2>报表设计</h2>
                        <p>系统数据报表设计与生成</p>
                    </div>
                    <div class="report-container">
                        <iframe 
                            src="http://localhost:8101/jmreport/list" 
                            frameborder="0" 
                            width="100%" 
                            height="800px"
                            class="report-iframe"
                        ></iframe>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Notification } from '@arco-design/web-vue'
import axios from '../../utils/http'
import OrderManagement from './OrderManagement.vue'
import MemberManagement from './MemberManagement.vue'

const router = useRouter()
const activeMenu = ref('message')
const adminInfo = ref({})
const sending = ref(false)

const messageForm = reactive({
    userId: null,
    messageTitle: '',
    messageContent: '',
    messageType: 1
})

const messageHistory = ref([])

const setActiveMenu = (menu) => {
    activeMenu.value = menu
}

const sendMessage = async () => {
    sending.value = true
    try {
        const requestData = {
            userId: messageForm.userId,
            messageTitle: messageForm.messageTitle,
            messageContent: messageForm.messageContent,
            messageType: messageForm.messageType
        }

        const response = await axios.get('/exam-message/notice/public/test/send', {
            data: requestData
        })
        
        if (response.success) {
            Notification.success({
                title: '发送成功',
                content: response.message || '消息已成功发送'
            })
            
            // 添加到发送历史
            messageHistory.value.unshift({
                title: messageForm.messageTitle || '测试通知',
                userId: messageForm.userId || 10,
                type: messageForm.messageType,
                time: new Date().toLocaleString(),
                status: 'success'
            })
            
            // 只保留最近10条记录
            if (messageHistory.value.length > 10) {
                messageHistory.value = messageHistory.value.slice(0, 10)
            }
            
            resetForm()
        } else {
            throw new Error(response.message || '发送失败')
        }
    } catch (error) {
        console.error('发送消息错误:', error)
        Notification.error({
            title: '发送失败',
            content: error.message || '网络错误，请稍后重试'
        })
        
        // 添加失败记录
        messageHistory.value.unshift({
            title: messageForm.messageTitle || '测试通知',
            userId: messageForm.userId || 10,
            type: messageForm.messageType,
            time: new Date().toLocaleString(),
            status: 'error'
        })
    } finally {
        sending.value = false
    }
}

const resetForm = () => {
    messageForm.userId = null
    messageForm.messageTitle = ''
    messageForm.messageContent = ''
    messageForm.messageType = 1
}

const getMessageTypeName = (type) => {
    const typeMap = {
        1: '普通通知',
        2: '重要通知',
        3: '紧急通知'
    }
    return typeMap[type] || '未知类型'
}

const logout = () => {
    localStorage.removeItem('adminToken')
    localStorage.removeItem('adminInfo')
    Notification.info({
        title: '已退出',
        content: '您已安全退出管理员控制台'
    })
    router.push('/admin/login')
}

onMounted(() => {
    // 检查登录状态
    const token = localStorage.getItem('adminToken')
    const info = localStorage.getItem('adminInfo')
    
    if (!token) {
        router.push('/admin/login')
        return
    }
    
    if (info) {
        try {
            adminInfo.value = JSON.parse(info)
        } catch (e) {
            console.error('解析管理员信息失败:', e)
        }
    }
})
</script>

<style lang="less" scoped>
.admin-dashboard {
    min-height: 100vh;
    background: var(--color-bg-1);
}

.admin-header {
    height: 60px;
    background: white;
    border-bottom: 1px solid var(--color-border-1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);

    .header-left {
        .logo-section {
            display: flex;
            align-items: center;

            .logo {
                height: 30px;
                width: 30px;
                margin-right: 12px;
            }

            .app-name {
                font-size: 18px;
                font-weight: 600;
                color: var(--color-text-1);
                margin: 0;
            }
        }
    }

    .header-right {
        display: flex;
        align-items: center;
        gap: 20px;

        .admin-info {
            color: var(--color-text-2);
            font-size: 14px;
        }

        .logout-btn {
            padding: 8px 16px;
            background: rgb(var(--red-6));
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;

            &:hover {
                background: rgb(var(--red-7));
            }
        }
    }
}

.admin-content {
    display: flex;
    min-height: calc(100vh - 60px);
}

.admin-sidebar {
    width: 200px;
    background: white;
    border-right: 1px solid var(--color-border-1);
    padding: 20px 0;

    .menu-list {
        .menu-item {
            display: flex;
            align-items: center;
            padding: 12px 20px;
            cursor: pointer;
            transition: all 0.3s;
            border-right: 3px solid transparent;

            .icon {
                margin-right: 12px;
                font-size: 16px;
            }

            span {
                font-size: 14px;
                color: var(--color-text-2);
            }

            &:hover {
                background: var(--color-fill-1);
            }

            &.active {
                background: rgb(var(--primary-1));
                border-right-color: rgb(var(--primary-6));
                
                span {
                    color: rgb(var(--primary-6));
                    font-weight: 500;
                }
            }
        }
    }
}

.admin-main {
    flex: 1;
    padding: 20px;
    background: var(--color-bg-2);
}

.module-content {
    .module-header {
        margin-bottom: 24px;

        h2 {
            font-size: 24px;
            font-weight: 600;
            color: var(--color-text-1);
            margin: 0 0 8px 0;
        }

        p {
            color: var(--color-text-3);
            margin: 0;
        }
    }
}

.message-form-card {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    margin-bottom: 24px;
}

.message-form {
    .form-row {
        display: flex;
        gap: 20px;
        margin-bottom: 20px;

        .form-group {
            flex: 1;
        }
    }

    .form-group {
        margin-bottom: 20px;

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--color-text-2);
        }

        input, select, textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid var(--color-border-2);
            border-radius: 6px;
            font-size: 14px;
            transition: all 0.3s;
            box-sizing: border-box;

            &:focus {
                outline: none;
                border-color: rgb(var(--primary-6));
                box-shadow: 0 0 0 3px rgba(var(--primary-6), 0.1);
            }
        }

        textarea {
            resize: vertical;
            min-height: 80px;
        }
    }

    .form-actions {
        display: flex;
        gap: 12px;
        justify-content: flex-start;

        .send-btn {
            padding: 10px 24px;
            background: rgb(var(--primary-6));
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;

            &:hover:not(:disabled) {
                background: rgb(var(--primary-7));
            }

            &:disabled {
                opacity: 0.6;
                cursor: not-allowed;
            }
        }

        .reset-btn {
            padding: 10px 24px;
            background: var(--color-bg-2);
            color: var(--color-text-2);
            border: 1px solid var(--color-border-2);
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;

            &:hover {
                background: var(--color-fill-1);
            }
        }
    }
}

.message-history {
    background: white;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);

    h3 {
        margin: 0 0 16px 0;
        color: var(--color-text-1);
        font-size: 16px;
    }

    .history-list {
        .history-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid var(--color-border-1);

            &:last-child {
                border-bottom: none;
            }

            .history-info {
                flex: 1;

                .history-title {
                    font-weight: 500;
                    color: var(--color-text-1);
                    margin-bottom: 4px;
                }

                .history-details {
                    font-size: 12px;
                    color: var(--color-text-3);
                }
            }

            .history-status {
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 12px;
                font-weight: 500;

                &.success {
                    background: rgb(var(--green-1));
                    color: rgb(var(--green-6));
                }

                &.error {
                    background: rgb(var(--red-1));
                    color: rgb(var(--red-6));
                }
            }
        }
    }
}

.report-container {
    background: white;
    border-radius: 8px;
    padding: 0;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    overflow: hidden;
    
    .report-iframe {
        display: block;
        border: none;
    }
}

@media screen and (max-width: 768px) {
    .admin-content {
        flex-direction: column;
    }

    .admin-sidebar {
        width: 100%;
        
        .menu-list {
            display: flex;
            overflow-x: auto;
            
            .menu-item {
                white-space: nowrap;
                border-right: none;
                border-bottom: 3px solid transparent;
                
                &.active {
                    border-right: none;
                    border-bottom-color: rgb(var(--primary-6));
                }
            }
        }
    }

    .message-form {
        .form-row {
            flex-direction: column;
            gap: 0;
        }
        
        .form-actions {
            flex-direction: column;
            
            button {
                width: 100%;
            }
        }
    }
}
</style>